package com.xxl.sso.server.service.impl;


import com.xxl.sso.server.core.api.BaseApiService;
import com.xxl.sso.server.core.constants.Constants;
import com.xxl.sso.server.core.dto.UserOutDTO;
import com.xxl.sso.server.core.entity.AppEntity;
import com.xxl.sso.server.core.entity.BaseResponse;
import com.xxl.sso.server.core.util.BeanUtils;
import com.xxl.sso.server.mapper.LoginLogMapper;
import com.xxl.sso.server.mapper.UploadDataMapper;
import com.xxl.sso.server.mapper.UserMapper;
import com.xxl.sso.server.mapper.UserTokenMapper;
import com.xxl.sso.server.mapper.entity.LoginLog;
import com.xxl.sso.server.mapper.entity.UploadData;
import com.xxl.sso.server.mapper.entity.UserDo;
import com.xxl.sso.server.mapper.entity.UserTokenDo;
import com.xxl.sso.server.service.AppService;
import com.xxl.sso.server.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;

@RestController
@Slf4j
public class MemberServiceImpl extends BaseApiService<UserOutDTO> implements MemberService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserTokenMapper userTokenMapper;

    @Autowired
    private LoginLogMapper loginLogMapper;

    @Autowired
//    private AppServiceFeign appServiceFeign;
    private AppService appService;

    @Autowired
    private UploadDataMapper uploadDataMapper;

    @Override
    public BaseResponse<UserOutDTO> existMobile(String mobile) {
        // 1.验证参数
        if (StringUtils.isEmpty(mobile)) {
            return setResultError("手机号码不能为空!");
        }

        // 2.根据手机号码查询用户信息 单独定义code 表示是用户信息不存在把
        UserDo userEntity = userMapper.existMobile(mobile);
        if (userEntity == null) {
            return setResultError(Constants.HTTP_RES_CODE_EXISTMOBILE_203, "用户信息不存在!");
        }
        // 3.将do转换成dto
        return setResultSuccess(BeanUtils.doToDto(userEntity, UserOutDTO.class));
    }

    @Override
    public BaseResponse<UserOutDTO> getInfo(String token) {

        UserTokenDo userTokenDo = userTokenMapper.selectByToken(token);
        if(userTokenDo == null){
            return setResultError("该用户没有登录!");
        }

        UserDo userDo = userMapper.findByUserId(userTokenDo.getUserId());
        if (userDo == null) {
            return setResultError("用户不存在!");
        }
        // 下节课将 转换代码放入在BaseApiService
        return setResultSuccess(BeanUtils.doToDto(userDo, UserOutDTO.class));
    }

    /**
     * 调用微信接口
     * @return
     */
    @Override
    @GetMapping("/memberInvokWeixin")
    public AppEntity memberInvokWeixin() {
        return appService.getApp();
    }

    @Override
    @GetMapping("/export/{docName}")
    public String exportMap(@PathVariable("docName") String docName, HttpServletResponse response) throws IOException, com.fasterxml.jackson.databind.exc.InvalidFormatException, com.fasterxml.jackson.databind.exc.InvalidFormatException {
        //下载之前先判断订单支付状态（由前端调用）
        //XWPFDocument，引入ooxml-schemas、poi才有效
        XWPFDocument document;
        String outPath = outPath = "/Users/wanghong/Desktop/文档发布/"+docName+".docx";
//        String outPath = outPath = "G:\\media\\doc\\"+docName+".docx";
        File file = new File(outPath);
        String filename = file.getName();
        FileInputStream fis = null;
        fis = new FileInputStream(file);
        //设置文件名及后缀
        response.setHeader("Content-Disposition", "attachment; filename=" +
                new String(filename.getBytes(), "ISO-8859-1"));
        response.setHeader("content-Type", "docx");
        String fileType = "docx";
        if ("docx".equals(fileType) || "doc".equals(fileType)) {//Office的doc与docx输出流，使用poi-ooxml 3.17可用
            try{
                document = new XWPFDocument(OPCPackage.open(fis));
                document.write(response.getOutputStream());
            }catch (InvalidFormatException e){
                e.printStackTrace();
            }

        }
        return null;
    }

    @Override
    public String  upload(@RequestParam("file") MultipartFile mf) {
        log.info("开始上传");
        //创建目录
        //存放在本地的固定目录，可考虑实现上传至远端服务器
        File uploadPath = new File("/Users/wanghong/Desktop/用户上传资料");
        //判断当前目录是否存在，不存在则新创建一个目录
        if (!uploadPath.exists()){
            uploadPath.mkdir();
        }
        if (!mf.isEmpty()){
            try{
                mf.transferTo(new File(uploadPath+"/"+mf.getOriginalFilename()));
            }catch (IOException e){
                e.getMessage();
            }
        }
        //添加记录
        //未完成与订单关联，添加订单编号
        UploadData uploadData = new UploadData();
        uploadData.setName(mf.getOriginalFilename());
        uploadData.setUrl("/literature/"+mf.getOriginalFilename());
        uploadData.setCreatedTime(new Date());
        uploadData.setUserId(1);
        uploadDataMapper.insert(uploadData);
        log.info("资料上传并已添加记录");
        return "{'result':'success'}";
    }

    @Override
    public String visitLog(String mobile) {

        // 保存登录日志
        LoginLog loginLog = new LoginLog();
        loginLog.setUsername(mobile);
        loginLog.setSystemBrowserInfo();
        loginLogMapper.insert(loginLog);

        return null;
    }
}
